import React, { useState, useEffect, useCallback } from 'react';
import { Table, Card, Spin, Alert, message, Modal, Button } from 'antd';
import { LineChartOutlined, EyeOutlined } from '@ant-design/icons';
import { getChangeAnalysisStats, ChangeAnalysisData } from '../../../services/changeAnalysis';
import { fetchMethodPageQuery } from '../../../services/method';
import { buildFileLink } from '../../../utils/gitUrlUtils';

interface ChangeAnalysisTabProps {
  unitId: string;
}

const ChangeAnalysisTab: React.FC<ChangeAnalysisTabProps> = ({ unitId }) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<ChangeAnalysisData | null>(null);
  const [error, setError] = useState<string | null>(null);
  
  // 弹框相关状态
  const [modalVisible, setModalVisible] = useState(false);
  const [modalLoading, setModalLoading] = useState(false);
  const [modalData, setModalData] = useState<any[]>([]);
  const [modalPagination, setModalPagination] = useState({ current: 1, pageSize: 10, total: 0 });
  const [modalTitle, setModalTitle] = useState('');
  const [timeRange, setTimeRange] = useState<'halfYear' | 'oneYear'>('halfYear');

  const fetchChangeAnalysisData = useCallback(async () => {
    if (!unitId) return;

    setLoading(true);
    setError(null);

    try {
      const result = await getChangeAnalysisStats(unitId);
      setData(result);
    } catch (err: any) {
      console.error('获取变更分析数据失败:', err);
      setError(err.message || '获取数据失败');
      message.error('获取变更分析数据失败');
    } finally {
      setLoading(false);
    }
  }, [unitId]);

  useEffect(() => {
    fetchChangeAnalysisData();
  }, [fetchChangeAnalysisData]);

  // 获取无调用API的详细方法列表
  const fetchZombieApiMethods = useCallback(async (range: 'halfYear' | 'oneYear', pager = { current: 1, pageSize: 10, total: 0 }) => {
    setModalLoading(true);
    
    try {
      // 构建查询参数：查询无调用的入口方法
      const params: any = {
        unitId,
        pageNum: pager.current,
        pageSize: pager.pageSize,
        isEntry: true, // 只查询入口方法（API）
      };
      
      // 根据时间范围设置不同的查询条件
      if (range === 'halfYear') {
        // 近半年：apm_last6m_count = 0 或 NULL
        params.apmLast6mCount = 0;
      } else {
        // 近一年：apm_last1y_count = 0 或 NULL
        params.apmLast1yCount = 0;
      }
      
      const res = await fetchMethodPageQuery(params);
      const dataRes = res.data || res;
      
      setModalData(dataRes.records || []);
      setModalPagination({ ...pager, total: dataRes.total || 0 });
    } catch (err: any) {
      console.error('获取无调用API方法列表失败:', err);
      message.error('获取方法列表失败');
    } finally {
      setModalLoading(false);
    }
  }, [unitId]);

  // 获取变更API的详细方法列表
  const fetchChangedApiMethods = useCallback(async (range: 'halfYear' | 'oneYear', pager = { current: 1, pageSize: 10, total: 0 }) => {
    setModalLoading(true);
    
    try {
      // 计算时间范围（天数）
      const days = range === 'halfYear' ? 180 : 365;
      
      // 构建查询参数：查询 git_last_edit_time 在时间范围内的API
      const params: any = {
        unitId,
        pageNum: pager.current,
        pageSize: pager.pageSize,
        isEntry: true, // 只查询入口方法（API）
        noCodeChangeDurationDays: days, // 累计无修改时长 <= 时间范围
        orderBy: 'noCodeChangeDurationDays',
        orderByType: 'asc'
      };
      
      const res = await fetchMethodPageQuery(params);
      const dataRes = res.data || res;
      
      setModalData(dataRes.records || []);
      setModalPagination({ ...pager, total: dataRes.total || 0 });
    } catch (err: any) {
      console.error('获取变更API方法列表失败:', err);
      message.error('获取方法列表失败');
    } finally {
      setModalLoading(false);
    }
  }, [unitId]);

  // 打开无调用API详情弹框
  const handleShowZombieApiDetail = (range: 'halfYear' | 'oneYear') => {
    setTimeRange(range);
    setModalTitle(range === 'halfYear' ? '近半年无调用API详情' : '近一年无调用API详情');
    setModalVisible(true);
    fetchZombieApiMethods(range);
  };

  // 打开变更API详情弹框
  const handleShowChangedApiDetail = (range: 'halfYear' | 'oneYear') => {
    setTimeRange(range);
    const rangeText = range === 'halfYear' ? '近半年' : '近一年';
    setModalTitle(`${rangeText}变更API详情`);
    setModalVisible(true);
    fetchChangedApiMethods(range);
  };

  // 弹框表格分页变化
  const handleModalTableChange = (pager: any) => {
    fetchZombieApiMethods(timeRange, { current: pager.current, pageSize: pager.pageSize, total: modalPagination.total });
  };

  const columns = [
    {
      title: '时间范围',
      dataIndex: 'timeRange',
      key: 'timeRange',
      width: 100,
      fixed: 'left' as const,
      render: (text: string) => <strong>{text}</strong>
    },
    {
      title: '变更代码量',
      dataIndex: 'codeLines',
      key: 'codeLines',
      width: 110,
      align: 'right' as const,
      render: (value: number) => value?.toLocaleString() || 0
    },
    {
      title: 'API统计',
      children: [
        {
          title: '变更API量',
          key: 'apiStats',
          width: 120,
          align: 'center' as const,
          render: (_: any, record: any) => {
            // 变更API量（已包含新增和修改）
            const totalChanged = record.apiChangeCount || 0;
            return totalChanged > 0 ? (
              <span
                onClick={() => handleShowChangedApiDetail(record.key)}
                style={{
                  color: '#1890ff',
                  cursor: 'pointer',
                  textDecoration: 'underline'
                }}
              >
                {totalChanged}
              </span>
            ) : (
              <span>{totalChanged}</span>
            );
          }
        },
        {
          title: '无调用API数量',
          key: 'zombieApi',
          width: 120,
          align: 'center' as const,
          render: (_: any, record: any) => (
            <span>
              {record.zombieApiCount > 0 ? (
                <span
                  onClick={() => handleShowZombieApiDetail(record.key)}
                  style={{
                    color: '#1890ff',
                    cursor: 'pointer',
                    textDecoration: 'underline'
                  }}
                >
                  {record.zombieApiCount}
                </span>
              ) : (
                <span>{record.zombieApiCount}</span>
              )}
              {' / '}
              {record.zombieApiRatio}
            </span>
          )
        },
        {
          title: '无调用API代码量',
          dataIndex: 'zombieApiCodeLines',
          key: 'zombieApiCodeLines',
          width: 130,
          align: 'right' as const,
          render: (value: number) => value?.toLocaleString() || 0
        }
      ]
    },
    {
      title: '方法统计',
      children: [
        {
          title: '变更方法量',
          dataIndex: 'methodChangeCount',
          key: 'methodChangeCount',
          width: 100,
          align: 'right' as const,
          render: (value: number) => value?.toLocaleString() || 0
        },
        {
          title: '无调用方法量',
          key: 'zombieMethod',
          width: 110,
          align: 'center' as const,
          render: (_: any, record: any) => `${record.zombieMethodCount} / ${record.zombieMethodRatio}`
        },
        {
          title: '无调用方法代码量',
          dataIndex: 'zombieMethodCodeLines',
          key: 'zombieMethodCodeLines',
          width: 130,
          align: 'right' as const,
          render: (value: number) => value?.toLocaleString() || 0
        }
      ]
    }
  ];

  const tableData = data ? [
    {
      key: 'halfYear',
      timeRange: '近半年',
      ...data.halfYear
    },
    {
      key: 'oneYear',
      timeRange: '近一年',
      ...data.oneYear
    }
  ] : [];

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '100px 0' }}>
        <Spin size="large" />
        <div style={{ marginTop: '16px' }}>加载变更分析数据中...</div>
      </div>
    );
  }

  if (error) {
    return (
      <Alert
        message="加载失败"
        description={error}
        type="error"
        showIcon
        style={{ margin: '20px' }}
        action={
          <button onClick={fetchChangeAnalysisData}>
            重试
          </button>
        }
      />
    );
  }

  // 弹框中的方法列表表格列定义
  const modalColumns = [
    {
      title: '包名',
      dataIndex: 'packageName',
      key: 'packageName',
      width: 200,
      ellipsis: true
    },
    {
      title: '类名',
      dataIndex: 'className',
      key: 'className',
      width: 150,
      ellipsis: true
    },
    {
      title: '方法名',
      dataIndex: 'methodName',
      key: 'methodName',
      width: 150,
      ellipsis: true
    },
    {
      title: '服务类型',
      dataIndex: 'serviceType',
      key: 'serviceType',
      width: 100,
      align: 'center' as const
    },
    {
      title: '累计无修改时长(天)',
      dataIndex: 'noCodeChangeDurationDays',
      key: 'noCodeChangeDurationDays',
      width: 150,
      align: 'right' as const,
      render: (value: number) => value || '-'
    },
    {
      title: '近半年变更行数',
      dataIndex: 'halfYearChangedLines',
      key: 'halfYearChangedLines',
      width: 130,
      align: 'right' as const,
      render: (value: number) => value?.toLocaleString() || 0
    },
    {
      title: '近一年变更行数',
      dataIndex: 'oneYearChangedLines',
      key: 'oneYearChangedLines',
      width: 130,
      align: 'right' as const,
      render: (value: number) => value?.toLocaleString() || 0
    },
    {
      title: 'APM半年调用量',
      dataIndex: 'apmLast6mCount',
      key: 'apmLast6mCount',
      width: 120,
      align: 'right' as const,
      render: (value: number) => value?.toLocaleString() || 0
    },
    {
      title: 'APM一年调用量',
      dataIndex: 'apmLast1yCount',
      key: 'apmLast1yCount',
      width: 120,
      align: 'right' as const,
      render: (value: number) => value?.toLocaleString() || 0
    },
    {
      title: 'SA首次发现时间',
      dataIndex: 'firstFoundTime',
      key: 'firstFoundTime',
      width: 150,
      align: 'center' as const,
      render: (value: string) => value || '-'
    },
    {
      title: 'SA最后调用时间',
      dataIndex: 'lastInvocationTime',
      key: 'lastInvocationTime',
      width: 150,
      align: 'center' as const,
      render: (value: string) => value || '-'
    },
    {
      title: 'SA累计扫描时长(小时)',
      dataIndex: 'saScannedUptimeMs',
      key: 'saScannedUptimeMs',
      width: 160,
      align: 'right' as const,
      render: (value: number) => {
        if (!value) return '-';
        // 将毫秒转换为小时，保留2位小数
        return (value / (1000 * 60 * 60)).toFixed(2);
      }
    },
    {
      title: '代码行数',
      dataIndex: 'totalLine',
      key: 'totalLine',
      width: 100,
      align: 'right' as const,
      render: (value: number) => value || 0
    }
  ];

  return (
    <>
      <Card
        title={
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <LineChartOutlined style={{ color: '#1890ff' }} />
            <span>变更分析统计</span>
          </div>
        }
        style={{ margin: '16px' }}
      >
        <div style={{ marginBottom: '16px', color: '#666', fontSize: '14px' }}>
          <p>展示单元在不同时间范围的代码、API、方法变更情况。无调用代码基于APM调用量数据判定。</p>
        </div>
        
        <Table
          columns={columns}
          dataSource={tableData}
          pagination={false}
          scroll={{ x: 1100 }}
          size="middle"
          bordered
        />
      </Card>

      {/* 无调用API详情弹框 */}
      <Modal
        title={modalTitle}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={1200}
        destroyOnClose
      >
        <Table
          columns={modalColumns}
          dataSource={modalData}
          loading={modalLoading}
          pagination={{
            current: modalPagination.current,
            pageSize: modalPagination.pageSize,
            total: modalPagination.total,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条`
          }}
          onChange={handleModalTableChange}
          scroll={{ x: 1800 }}
          size="small"
          rowKey="id"
        />
      </Modal>
    </>
  );
};

export default ChangeAnalysisTab;